<template>
	<view>
		<u-navbar title="发起回收" @leftClick="leftClick" bgColor="transparent"
			:titleStyle="{fontSize:'36rpx',fontWeight:'500'}">
		</u-navbar>
		<scroll-view class="container" :scroll-y="true">
			<view v-show="curPage===1">
				<view class="address" @tap="goAddress">
					<view class="left">
						<u-icon name="map-fill" color="#0080FF" size="28"></u-icon>
					</view>
					<view class="center" v-if="defaultAddress!==null">
						<view class="name_line">
							<u--text size="16" :text="defaultAddress.person+'  '+defaultAddress.mobile"></u--text>
						</view>
						<view class="address_line">
							<u--text :lines="2" lineHeight="20" size="14"
								:text="defaultAddress.province+defaultAddress.city+defaultAddress.district+defaultAddress.address"></u--text>
						</view>
					</view>
					<view class="center add_address" v-else>
						<view class="address_line">
							<u--text size="18" text="添加回收地址"></u--text>
						</view>
					</view>
					<view class="right">
						<u-icon name="arrow-right" color="#DDDDDD" size="14"></u-icon>
					</view>
				</view>
				<view class="title">
					<u--text lineHeight="30" bold size="16" text="施工内容"></u--text>
				</view>
				<u--form class="uForm" :model="order" :rules="rules" ref="uForm">
					<u-form-item prop="category" :borderBottom='false' @click="showCategory = true; hideKeyboard()"
						ref="category">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>产品类型</text>
						</template>
						<u--input v-model="order.category" disabled disabledColor="#ffffff" placeholder="请选择产品类型"
							border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item prop="levelA" :borderBottom='false' ref="levelA">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>A级</text>
						</template>
						<u--input v-model="order.levelA" border="none" placeholder="请输入数量"></u--input>
					</u-form-item>
					<u-form-item label="B级" prop="levelB" :borderBottom='false' ref="levelB">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>B级</text>
						</template>
						<u--input v-model="order.levelB" border="none" placeholder="请输入数量"></u--input>
					</u-form-item>
					<u-form-item label="C级" prop="levelC" :borderBottom='false' ref="levelC">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>C级</text>
						</template>
						<u--input v-model="order.levelC" border="none" placeholder="请输入数量"></u--input>
					</u-form-item>
					<u-form-item prop="time" :borderBottom='false' @click="showTimePicker = true; hideKeyboard()"
						ref="time">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>可取货日期</text>
						</template>
						<u--input v-model="order.time" disabled disabledColor="#ffffff" placeholder="请选择日期"
							border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<view>
						<view class="no-required-label"><text>备注信息</text></view>
						<u--textarea border="none" v-model="order.remark" placeholder="请输入备注信息" count
							maxlength='200'></u--textarea>
					</view>
					<u-form-item prop="img" :borderBottom='false' @click="photoSelect" ref="img">
						<template v-slot:label>
							<text class="required-label">上传图片</text>
						</template>
						<u--input v-model="order.img" disabled disabledColor="#ffffff" placeholder="仅限jpg、png格式"
							border="none"></u--input>
						<u-icon slot="right" name="photo" color="#0080FF" size="20"></u-icon>
					</u-form-item>

            <view v-for="(item,index) in order.file_id" :key="index"
                  style="display: inline-block;width: 49.9%;position: relative;">
              <view>
                <u-album :urls="['https://www.scivisco.com/prod-api/api/download/'+item]" style="width: 100%"></u-album>
              </view>
              <view class="img_delete">
                <image src="../../static/shanchu.png" @click="deleteImg(index)" style="width: 100%;height: 100%"></image>
              </view>
            </view>
				</u--form>

			</view>
			<view v-show="curPage===2">
				<u--form class="uForm2" :model="order" ref="uForm2">
					<u-form-item prop="category" :borderBottom='false' @click="showPayType = true; hideKeyboard()"
						ref="category">
						<template v-slot:label>
							<text class="required-label"><text class="required-star">*</text>收款方式</text>
						</template>
						<u--input v-model="order.pay_type_cn" disabled disabledColor="transparent" placeholder="请选择收款方式"
							border="none"></u--input>
					</u-form-item>
				</u--form>
				<view class="sumPrice">
					<view class="top">
						<view class="price">
							<view class="p_title">
								<u--text text="预估回收金额 (元)" color="#fff"></u--text>
							</view>
							<view class="p_num">
								<u--text mode="price" :text="price" color="#fff" size="24"></u--text>
							</view>
						</view>
						<view class="pay_type" v-if="order.pay_type_cn!==''">
							<u--text :text="order.pay_type_cn" color="#fff" size="12" bold align="center"></u--text>
						</view>
					</view>
					<view class="bottom">
						<u--text :lines="1" :text="remark" color="#fff"></u--text>
					</view>
				</view>
				<view class="stepDiv">
					<view class="title">
						<u--text lineHeight="30" bold size="16" text="计算过程"></u--text>
					</view>
					<view class="step" v-for="(item,index) in computation" :key="index">
						<view class="stepCate">
							<u--text lineHeight="30" bold size="15" :text="item.name"></u--text>
						</view>
						<view class="stepDesc">
							<u--text lineHeight="30" size="15" :text="item.price"></u--text>
						</view>
					</view>
					<view class="explanation">
						<u--text lineHeight="20" size="10" color="#979797" text="说明:"></u--text>
						<u--text lineHeight="20" size="10" color="#979797"
							text="目前我司仅接收公对公打款，收款时您需开具相应的增值税发票(13%税点);"></u--text>
						<u--text lineHeight="20" size="10" color="#979797"
							text="托盘经过现场回收人员盘点分级后得出实际金额;"></u--text>
						<!-- <u--text lineHeight="20" size="10" color="#979797"
							text="若选择公对私收款方式，将会在上述总计金额的基础上扣除13%的税费;"></u--text> -->
					</view>
				</view>
			</view>
			<view v-show="curPage===3">
				<view class="orderFinish">
					<view class="order_tips">
						<u--text color="#fff" text="已提交成功" size="18"></u--text>
						<u--image src="/static/submitSuccess.png" width="60rpx" height="60rpx"></u--image>
					</view>
					<view class="order_msg">
						<u--text text="我司人员将会在5个工作日内再次与您联系，请保持电话畅通;" color="#fff" size="10"></u--text>
					</view>
				</view>
				<view class="order_detail">
					<view class="line"></view>
					<view class="order_info">
						<view class="item">
							<u--text text="预估回收金额:" color="#979797" size="14"></u--text>
							<u--text text="总计" size="14"></u--text>
							<u--text mode="price" :text="price" size="18"></u--text>
						</view>
						<view class="item">
							<u--text text="收款方式:" color="#979797" size="14"></u--text>
							<u--text text="公对公" color="#979797" size="14"></u--text>
						</view>
					</view>
					<view class="tips_text">
						<text :style="{color:'#979797'}">您也可在</text>
						<text :style="{color:'#0080FF'}" @tap="goRecyclingForm">我的--回收单管理</text>
						<text :style="{color:'#979797'}">查看对应的回收单信息</text>
					</view>

					<view class="finishBtn">
						<u-button type="primary" text="我知道了" @tap="backToRecycle"></u-button>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="bottomBtnDiv">
			<view class="bottomBtn" v-show="curPage===1">
				<u-button type="primary" text="下一步" @tap="nextStep"></u-button>
			</view>
			<view class="bottomBtn" v-show="curPage===2">
				<u-button type="primary" text="确认回收" @tap="submitOrder"></u-button>
			</view>
		</view>
		<u-action-sheet :show="showCategory" :actions="product_categories" title="请选择产品类型"
                    @close="showCategory = false"
			@select="categorySelect">
		</u-action-sheet>
		<u-datetime-picker :show="showTimePicker" :minDate="minDate" mode="date"
			@confirm="timeSelect"></u-datetime-picker>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import dayjs from 'dayjs';
	import {
		getProducts,
		getAddress,
		getLevelPrices
	} from "@/api/user.js";
	import {
		uploadImg,
		saveOrder
	} from "@/api/index.js";
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	export default {
		computed: {
			...mapState(["user", 'tokenInfo'])
		},
		data() {
			return {
				curPage: 1,
				defaultAddress: null,
				address: [],
				minDate: Date.now(),
				showTimePicker: false,
				showCategory: false,
				showPayType: false,
				order: {
					category_id: 0,
					category: '',
					'levelA': null,
					'A-level': 0,
					'levelB': null,
					'B-level': 0,
					'levelC': null,
					'C-level': 0,
					time: "",
					remark: "",
					img: "",
					pay_type: 0,
					pay_type_cn: "公对公",
					file_id: []
				},
				product_categories: [{
						name: '类型1',
						id: 1
					},
					{
						name: '类型2',
						id: 2
					},
					{
						name: '类型3',
						id: 3
					},
				],
				pay_actions: [{
						name: '公对公',
						id: 1
					},
					{
						name: '公对私',
						id: 2
					}
				],
				rules: {
					'category': {
						type: 'string',
						required: true,
						message: '请选择分类',
						trigger: ['blur', 'change']
					},
					'time': {
						type: 'string',
						required: true,
						message: '请确认可取货时间',
						trigger: ['blur', 'change']
					},
					'levelA': {
						type: 'number',
						required: true,
						message: '请填写A级数量',
						trigger: ['blur', 'change']
					},
					'levelB': {
						type: 'number',
						required: true,
						message: '请填写B级数量',
						trigger: ['blur', 'change']
					},
					'levelC': {
						type: 'number',
						required: true,
						message: '请填写C级数量',
						trigger: ['blur', 'change']
					},
				},
				remark: "公对公(含13%增值税)",
				price: 0,
				computation: [],
        dialogVisible:false,//确认删除图片的弹窗
        selectedImageId:null,//被删除的图片id
			};
		},
		onLoad(option) {
      // 查询默认地址
      this.getAddresses();
			this.getProducts();
			getLevelPrices({}).then(res => {
				res.data.forEach(item => {
					this.order[item.name] = item.value
				})
			}).catch(err => {
				console.error(err)
			})
		},
		mounted() {
      uni.$on('ref',(data)=>{
        console.log("传递了",data)
        // 检查是否是从 地址页返回的 并赋值数据
        if(data.data){
          this.defaultAddress = data.data
        }else{
          this.defaultAddress = null
        }
      })
    },
		methods: {
      // 处理删除事件
      deleteImg(index) {
        this.order.file_id.splice(index, 1)
      },
      generateImageUrls(fileIds) {
        // 生成图片 URL 数组
        if (Array.isArray(fileIds) && fileIds.length > 0) {
          return fileIds.map(id => 'https://www.scivisco.com/prod-api/api/download/' + id);
        }
        // 如果没有有效的 ID，返回空数组
        return [];
      },
			hideKeyboard() {
				uni.hideKeyboard();
			},
			getProducts() {
				let query = {
					user_id: this.user.id
				};
				getProducts(query).then(res => {
					this.product_categories = res.data.map(item => {
						return {
							name: item.category2,
							id: item.id
						}
					});
				}).catch(err => {
					console.error(err);
				})
			},
			getAddresses() {
				let query = {
					username: this.user.username
				};
				getAddress(query).then(res => {
					let defaultAdd = res.data.find(item => {
						return item.is_default == 1
					})
					this.address = JSON.parse(JSON.stringify(res.data));
					if (defaultAdd !== undefined) {
						this.defaultAddress = defaultAdd;
					} else {
						if (res.data.length > 0) {
							this.defaultAddress = res.data[0];
						} else {
							this.defaultAddress = null;
						}
					}
				}).catch(err => {
					console.error(err);
				})
			},
			leftClick() {
				uni.navigateBack();
			},
			nextStep() {
        this.$refs.uForm.validate().then(res => {
          if(this.defaultAddress){
            this.curPage++;
            if (this.curPage == 2) {
              let sumPrice = 0;
              if (this.order.levelA > 0) {
                this.computation.push({
                  name: "循环托盘" + this.order.category + " A类",
                  price: "回收单价" + this.order['A-level'] + "元/块 " + this.order['A-level'] + "x" +
                      this.order.levelA + "=" + this.order['A-level'] * this.order.levelA + "元"
                })
                sumPrice += this.order['A-level'] * this.order.levelA;
              }
              if (this.order.levelB > 0) {
                this.computation.push({
                  name: "循环托盘" + this.order.category + " B类",
                  price: "回收单价" + this.order['B-level'] + "元/块 " + this.order['B-level'] + "x" +
                      this.order.levelB + "=" + this.order['B-level'] * this.order.levelB + "元"
                })
                sumPrice += this.order['B-level'] * this.order.levelB;
              }
              if (this.order.levelC > 0) {
                this.computation.push({
                  name: "循环托盘" + this.order.category + " C类",
                  price: "回收单价" + this.order['C-level'] + "元/块 " + this.order['C-level'] + "x" +
                      this.order.levelC + "=" + this.order['C-level'] * this.order.levelC + "元"
                })
                sumPrice += this.order['C-level'] * this.order.levelC;
              }
              this.price = sumPrice;
            }
          }else{
            uni.$u.toast('请添加回收地址')
          }
        }).catch(errors => {
          uni.$u.toast('请填写完整的数据')
        })
			},
      // 确认回收
			submitOrder() {
				let query = {
					"conds": [
              {
						"col": "no_recycle", //回收单号
						"val": "RMR", //回收单单别（这个需要产品定义，这里只是举例）
						"service": "autoOrder" //固定值
					}, {
						"col": "state_recycle", //单据状态
						"val": "00" //固定值
					}, {
						"col": "id_out_addr", //地址ID
						"val": this.defaultAddress.id
					}, {
						"col": "type_pay", //支付方式
						"val": "00" //00 公对公，01 公对私
					}, {
						"col": "rate_pay", //税率
						"val": "13"
					}, {
						"col": "amount_pay", //金额
						"val": this.price
					}, {
						"col": "datetime_recycle", //可取货时间
						"val": this.order.time
					}, {
						"col": "remark", //备注
						"val": this.order.remark
					}],
					"A-level": [
              { //A级
						"col": "id_sku", //sku_id
						"val": this.order.category_id
					}, {
						"col": "level_product", //级别
						"val": "00" // 固定值00 代表A级
					}, {
						"col": "num_recycle", //数量
						"val": this.order.levelA
					}, {
						"col": "price_recycle", //单价
						"val": this.order['A-level']
					}],
					"B-level": [
              { //B级
						"col": "id_sku", //sku_id
						"val": this.order.category_id
					}, {
						"col": "level_product", //级别
						"val": "01" // 固定值01 代表B级
					}, {
						"col": "num_recycle", //数量
						"val": this.order.levelB
					}, {
						"col": "price_recycle", //单价
						"val": this.order['B-level']
					}],
					"C-level": [
              {
						"col": "id_sku", //sku_id
						"val": this.order.category_id
					}, {
						"col": "level_product", //级别
						"val": "02" // 固定值02 代表C级
					}, {
						"col": "num_recycle", //数量
						"val": this.order.levelC
					}, {
						"col": "price_recycle", //单价
						"val": this.order['C-level']
					}],
					"file_id": this.order.file_id, //附件id
				};
				saveOrder(query).then(res => {
          if (res.code==0){
            this.nextStep();
          }else{
            uni.showToast({
              title:res.msg,
              icon: 'none',
            });
          }

				}).catch(err => {
					console.error(err)
				})
			},
			showToast(text, type = "default") {
				this.$refs.uToast.show({
					type: type,
					message: text
				})
			},
			categorySelect(e) {
				this.order.category = e.name
				this.order.category_id = e.id;
				this.$refs.uForm.validateField('category')
			},
			payTypeSelect(e) {
				this.order.pay_type_cn = e.name
				this.order.pay_type = e.id;
				if (e.id == 2) {
					this.remark = "您选择的收款方式为公对私(含13%增值税)";
				} else {
					this.remark = "您选择的收款方式为公对公(需开具增值税发票)"
				}
				this.$refs.uForm2.validateField('pay_type_cn')
			},
			timeSelect(e) {
				this.order.time = dayjs(e.value).format("YYYY-MM-DD");
				this.showTimePicker = false
			},
			photoSelec1(e) {
				uni.chooseImage({
					count: 9,
					sizeType: ['compressed'],
					extension: ['jpg', 'png'],
					success: (imgs) => {
						uploadImg(imgs.tempFilePaths, {
							'table_name': 'ope_recycle'
						}).then(res => {
              console.log('返回结果111',res)
							let id = res.data.id
							this.order.file_id.push(id);
						}).catch(err => {
							console.error(err);
						});
					}
				})
			},
      photoSelect(e) {
        uni.chooseImage({
          count: 9, // 设置最多选择9张图片
          sizeType: ['compressed'],
          extension: ['jpg', 'png'],
          success: (imgs) => {
            // 创建一个数组用于存储上传的 Promise
            let uploadPromises = imgs.tempFilePaths.map(tempFilePath => {
              return uploadImg(tempFilePath, {
                'table_name': 'ope_recycle'
              }).then(res => {
                return res.data.id
              });
            });
            // 使用 Promise.all 等待所有上传完毕
            Promise.all(uploadPromises)
                .then(results  => {
                  results.forEach(item => {
                    this.order.file_id.push(item);
                  });
                })
                .catch(err => {
                  console.error(err);
                });
          }
        });
      },
			goRecyclingForm() {
				uni.navigateTo({
					url: '/pagesB/recycling/recycling_forms'
				})
			},
			goAddress() {
        let text = '回收页'
        const url = `/pages/mine/address_management?text=${text}`;
        uni.navigateTo({
          url: url
        });
			},
			backToRecycle() {
				uni.switchTab({
					url: '/pages/recycle/recycle'
				})
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	}
</script>

<style lang="scss" scoped>
.img_delete{
  width: 20px;
  height: 20px;
  display: inline-block;
  position: absolute;
  line-height: 20px;
  left:0;
  top: 0;
  z-index: 2;
  text-align: center;
  border-radius: 50%;
  background-color: white;
}
	.address {
		height: 212rpx;
		background: url(/static/bottom_line.png) no-repeat bottom center;
		background-size: 100% 8rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.left {
			width: 120rpx;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.center {
			box-sizing: border-box;
			padding: 48rpx 0 40rpx;
			width: 514rpx;
			height: 100%;

			.name_line {
				margin-bottom: 20rpx;
			}

			&.add_address {
				padding-top: 40rpx;
				display: flex;
				align-items: center;
			}
		}

		.right {}
	}

	.title {
		margin: 40rpx 0;
	}

	.required-label {
		display: flex;
		align-items: center;
		width: 232rpx;
		font-size: 28rpx;
		font-weight: 400;

		.required-star {
			color: red;
		}
	}

	.no-required-label {
		margin: 20rpx 0;
	}

	.uForm {
		margin-bottom: 80rpx;
	}

	.bottomBtnDiv {
		bottom: 60rpx;
    background-color: white;
    z-index: 10;
	}

	.sumPrice {
		width: 638rpx;
		// height: 214rpx;
		margin: 48rpx auto 40rpx;
		border-radius: 16rpx;
		background: linear-gradient(to right, #3D88FF, #97BDFC);
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;

		.top {
			position: relative;
			box-sizing: border-box;
			padding: 28rpx;
			width: 100%;
			// height: 146rpx;
			flex-shrink: 0;
			flex-grow: 0;

			.price {
				color: #fff;

				.p_title {
					margin-bottom: 24rpx;
				}
			}

			.pay_type {
				position: absolute;
				top: 48rpx;
				right: 28rpx;
				background: rgba(255, 255, 255, 0.3);
				width: 120rpx;
				height: 48rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 16rpx;
			}
		}

		.bottom {
			flex-shrink: 0;
			flex-grow: 0;
			background: rgba(255, 255, 255, 0.1);
			border-bottom-left-radius: 16rpx;
			border-bottom-right-radius: 16rpx;
			box-sizing: border-box;
			padding: 0 28rpx;
			font-size: 20rpx;
			width: 100%;
			height: 60rpx;
			display: flex;
			align-items: center;
		}
	}

	.stepDiv {
		width: 638rpx;
		margin: 0 auto 40rpx;

		.step {
			padding: 0 24rpx;
			margin-bottom: 20rpx;
		}

		.explanation {
			margin-top: 80rpx;
		}
	}

	.orderFinish {
		position: relative;
		background: #0080FF;
		border-radius: 16rpx;
		padding: 0 28rpx 138rpx;

		.order_tips {
			box-sizing: border-box;
			padding: 54rpx 0 22rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}


	}

	.order_detail {
		position: relative;
		z-index: 1;
		margin: -108rpx auto 0;
		width: 638rpx;

		.line {
			height: 24rpx;
			border-radius: 32rpx;
			background: #2E6EE9;
		}

		.order_info {
			position: relative;
			z-index: 1;
			background: url(/static/info_bg.png) no-repeat top center;
			background-size: 100% auto;
			margin: -12rpx auto 40rpx;
			box-sizing: border-box;
			padding: 52rpx 28rpx 12rpx;
			width: 598rpx;

			.item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 48rpx;
			}
		}

		.tips_text {
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;
		}

		.finishBtn {
			margin-top: 196rpx;
		}
	}
</style>
